﻿import { Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {  ComboboxItemDto,  CreateOrUpdateOrderDto, OrderServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import { from } from 'rxjs';

@Component({
    selector: 'createOrEditOrderModal',
    templateUrl: './create-or-edit-Order-modal.component.html'
})
export class CreateOrEditOrderModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('deliveryDatePicker') deliveryDatePicker: ElementRef;
    @ViewChild('customerCombobox') CustomergeCombobox: ElementRef;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    order: CreateOrUpdateOrderDto = new CreateOrUpdateOrderDto();
    customers: ComboboxItemDto[] = [];
    deliveryTime :string ='';

    constructor(
        injector: Injector,
        private _orderServiceProxy: OrderServiceProxy
    ) {
        super(injector);
    }

    show(orderId?: number): void {
        this.active = true;
        this._orderServiceProxy.getOrderForEdit(orderId).subscribe(result => {
            this.order = result;
            this.deliveryTime = result.deliveryTime.format('YYYY/MM/DD');
            this.customers = result.customers;
            this.modal.show();     

        });

    }

    save(): void {       
        this.saving = true;
        this.order.deliveryTime = moment(this.deliveryTime).add(1,'day');
        this._orderServiceProxy.createOrUpdateOrder(this.order)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
